package com.yourenbang.lingyun.transaction.web.service.impl.pay.withdraw;

import com.yourenbang.lingyun.mapper.FundAccountMapper;
import com.yourenbang.lingyun.transaction.config.DingdingConfig;
import com.yourenbang.lingyun.transaction.mapper.TransactionFundAccountChangePlanMapper;
import com.yourenbang.lingyun.transaction.mapper.TransactionFundAccountMapper;
import com.yourenbang.lingyun.transaction.mapper.TransactionFundAccountWithdrawPaymentMapper;
import com.yourenbang.lingyun.transaction.web.service.pay.withdraw.WithdrawFundOptService;
import com.yourenbang.lingyun.transaction.web.service.pay.withdraw.WithdrawFundService;
import com.yourenbang.transaction.api.service.fund.FundBillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service("fundWithdrawService")
public class WithdrawFundServiceImpl implements WithdrawFundService {

    @Autowired
    private DingdingConfig dingdingConfig;
    @Autowired
    private FundAccountMapper fundAccountMapper;
    @Autowired
    private TransactionFundAccountMapper transactionFundAccountMapper;
    @Autowired
    private TransactionFundAccountChangePlanMapper fundAccountChangePlanMapper;
    @Autowired
    private TransactionFundAccountWithdrawPaymentMapper fundAccountWithdrawPaymentMapper;
    @Autowired
    private WithdrawFundOptService withdrawFundOptService;
    @Autowired
    private FundBillService fundBillService;

    /**
     * 可提余额冻结
     */

//    public Result<FundPayBusVO> balanceFundPay(FundPayBusDTO dto) {
//
//        KLog.info("【提现】可提余额冻结, 入参:{}", dto.toJSON());
//
//        FundPayBusVO busVO = new FundPayBusVO();
//
//
//        Integer fromAccountType = WithdrawAccountConfig.formatSysAccountType(dto.getWithdrawType(), dto.getPlatNo());
//        FundAccount sysAccount = transactionFundAccountMapper.getSysAccountByType(fromAccountType);
//        if (Objects.isNull(sysAccount)) {
//            KLog.warn("【提现】可提余额冻结, 提现账户不存在, 入参:{}", dto.toJSON());
//            return Result.builder().fail(BizCodeMessages.TRANSACTION_ACCOUNT_NONE, "系统账户不存在", busVO);
//        }
//
//        if (!sysAccount.getAccountStatus().equals(TsFundAccount.ACCOUNT_STATUS_ON)) {
//            KLog.warn("【提现】可提余额冻结, 通易付系统支付宝押金提现账户状态为[{}], 入参:{}", sysAccount.getAccountStatus(), dto.toJSON());
//            return Result.builder().fail(BizCodeMessages.TRANSACTION_ACCOUNT_STATUS_OFF, "系统账户状态异常", busVO);
//        }
//
//        //用户账户
//        Integer toAccountType = WithdrawAccountConfig.formatUserAccountType(dto.getWithdrawType(), dto.getPlatNo());
//        FundAccount userAccount = transactionFundAccountMapper.getUserAccountByType(dto.getUserId(), toAccountType);
//        if (userAccount == null) {
//            KLog.warn("【提现】可提余额冻结, 用户账户不存在, 入参:{}", dto.toJSON());
//            return Result.builder().fail(BizCodeMessages.TRANSACTION_ACCOUNT_NONE, "用户账户不存在", busVO);
//        }
//        busVO.setFundAccountId(userAccount.getFundAccountId());
//
//        if (!userAccount.getAccountStatus().equals(TsFundAccount.ACCOUNT_STATUS_ON)) {
//            KLog.warn("【提现】可提余额冻结, 用户账户状态为[{}], 入参:{}", userAccount.getAccountStatus(), dto.toJSON());
//            return Result.builder().fail(BizCodeMessages.TRANSACTION_ACCOUNT_STATUS_OFF, "用户账户状态异常", busVO);
//        }
//
//        //设置 到账金额,手续费
//        WithdrawInAmountFeeVO feeVO = WithdrawAccountConfig.withdrawInAmountFeeVO(userAccount.getAccountType(), dto.getWithdrawType());
//        BigDecimal fee = dto.getAmount().multiply(feeVO.getWithdrawRate()).setScale(2, RoundingMode.HALF_UP).add(feeVO.getWithdrawFixedAmt());
//        busVO.setFee(fee);
//        busVO.setInAmount(dto.getAmount().subtract(fee));
//
//        if (userAccount.getAccountAmountWithdrawable().compareTo(dto.getAmount()) < 0) {
//
//            KLog.warn("【提现】可提余额冻结, 用户账户资金不足, 入参:{}", dto.toJSON());
//
//            return Result.builder().fail(BizCodeMessages.TRANSACTION_AMOUNT_DEFICIENCY, "用户账户资金不足", busVO);
//        }
//
//        //系统账户资金不足
//        if (sysAccount.getAccountAmountWithdrawable().compareTo(dto.getAmount()) < 0) {
//
//            KLog.warn("【提现】可提余额冻结, 系统账户资金不足, 入参:{}", dto.toJSON());
//            StringBuilder dingMark = new StringBuilder("【账户余额不足预警】");
//            dingMark.append(PlatNoEnums.getPlatNo(sysAccount.getPlatNo()).getName());
//            dingMark.append(sysAccount.getAccountName());
//            dingMark.append("余额已不足,请尽快充值!");
//            DingdingUtils.sendToDingding(dingMark.toString(), dingdingConfig.getDingdingWarnToken());
//
//            return Result.builder().fail(BizCodeMessages.TRANSACTION_AMOUNT_DEFICIENCY, "系统维护中,请稍后再试", busVO);
//        }
//
//
//        FundAccountChangePlan changePlan = new FundAccountChangePlan(userAccount.getPlatNo());
//        changePlan.setFundAccountId(sysAccount.getFundAccountId());
//        changePlan.setToFundAccountId(userAccount.getFundAccountId());
//
//        changePlan.setAccountJournalType(WithdrawAccountConfig.formatChangePlanAccountJournalType(dto.getWithdrawType(), dto.getPlatNo()));
//        changePlan.setAccountJournalTypeName(AccountJournalType.getAccountJournalTypeByFullCode(changePlan.getAccountJournalType()).getMsg());
//
//        changePlan.setFromAccountJournalType(WithdrawAccountConfig.formatSysAccountJournalType(dto.getWithdrawType(), dto.getPlatNo()));
//        changePlan.setFromAccountJournalTypeName(AccountJournalType.getAccountJournalTypeByFullCode(changePlan.getFromAccountJournalType()).getMsg());
//
//        changePlan.setOrderId(dto.getOrderNo());
//        changePlan.setChangeAmount(dto.getAmount());
//        changePlan.setChannelId(ChannelIdEnums.no.getCode());
//        changePlan.setAccountChangePlanStatus(ChangePlanStatus.CHANGING);   //变动中
//
//        int inChangePlan30 = fundAccountChangePlanMapper.insert(changePlan);
//        BizAssertUtils.assertOne(inChangePlan30, "添加资金变动失败");
//
//        busVO.setFundAccountChangePlanId(changePlan.getFundAccountChangePlanId());
//
//        try {
//            //账户操作
//            withdrawFundOptService.balanceFundPayOpt(sysAccount, userAccount, changePlan, dto);
//        } catch (Exception e) {
//            KLog.error("【提现】可提余额冻结,异常:{}, 资金变动记录:{}", e.getMessage(), changePlan.toString(), e);
//            return Result.builder().fail(BizCodeMessages.TRANSACTION_PLEDGE_CHECKING, busVO);
//        }
//
//        KLog.info("【提现】可提余额冻结, 出参:{}, 入参:{}", busVO.toJSON(), dto.toJSON());
//        return Result.builder().success(busVO);
//    }

    /**
     * 归还冻结金额
     */
//    @Override
//    public Result<Void> returnFund(Integer fundAccountWithdrawPaymentId, Short platNo) {
//
//        KLog.info("【提现】归还冻结金额, fundAccountWithdrawPaymentId:{}", fundAccountWithdrawPaymentId);
//
//        FundAccountWithdrawPayment withdrawPayment = fundAccountWithdrawPaymentMapper.selectByPrimaryKey(platNo, fundAccountWithdrawPaymentId);
//
//        FundAccountChangePlan changePlan = fundAccountChangePlanMapper
//                .getByOrderId(platNo, withdrawPayment.getOrderSn());
//        if (Objects.isNull(changePlan)) {
//            KLog.warn("【提现】归还冻结金额异常, 资金变动计划为空:{}", fundAccountWithdrawPaymentId);
//            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "资金变动计划为空");
//        }
//        changePlan.setPlatNo(platNo);
//
//
//        //用户账户
//        FundAccount fundAccount = fundAccountMapper.selectByPrimaryKey(withdrawPayment.getFundAccountId());
//
//        //设置资金主类型
//        Integer accountMainJournalType = null;
//        if (AccountType.getFullCode(AccountType.MER, PlatNoEnums.YXY.getCode()).equals(fundAccount.getAccountType())) {
//            accountMainJournalType = AccountMainJournalType.MERCHANT_REFUND.getCode();
//        } else {
//            accountMainJournalType = AccountMainJournalType.ALLY_REFUND.getCode();
//        }
//        changePlan.setAccountMainJournalType(accountMainJournalType);
//
//        JournalInfoVO journalVO = ChangeTypeConstant.getAddJournalTypeV2(fundAccount.getAccountType(), accountMainJournalType);
//        changePlan.setAccountJournalType(journalVO.getToJournalType());
//        changePlan.setAccountJournalTypeName(journalVO.getUserJournalTypeName());
//        changePlan.setFromAccountJournalType(journalVO.getFromJournalType());
//        changePlan.setFromAccountJournalTypeName(journalVO.getSysJournalTypeName());
//
//
//        try {
//            //账户操作
//            withdrawFundOptService.returnFundOpt(changePlan);
//        } catch (BizRuntimeException e) {
//            KLog.warn("【提现】归还冻结金额,异常:{}, 资金变动记录:{}", e.getMessage(), changePlan.toString(), e);
//            throw e;
//        } catch (Exception e) {
//            KLog.warn("【提现】归还冻结金额,异常:{}, 资金变动记录:{}", e.getMessage(), changePlan.toString(), e);
//            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "冻结金额已归还,无需重复归还");
//        }
//
//        //账单
//        AddBillDTO billDTO = AddBillDTO.builder()
//                .userBaseId(fundAccount.getUserBaseId())
//                .fundAccountId(withdrawPayment.getFundAccountId())
//                .fundAccountChangePlanId(withdrawPayment.getFundAccountChangePlanId())
//                .orderId(withdrawPayment.getOrderSn())
//                .amount(withdrawPayment.getAmount())
//                .billType(FundBillType.TYPE_201)
//                .showFlag(false)
//                .channelId(ChannelIdEnums.no.getCode())
//                .platNo(platNo)
//                .build();
//
//
//        billDTO.setShowFlag(true);
//        billDTO.setAccountMainJournalType(accountMainJournalType);
//        billDTO.setAccountMainJournalTypeName(AccountMainJournalType.getMainJournalTypeByCode(billDTO.getAccountMainJournalType()).getName());
//        billDTO.setAccountJournalType(changePlan.getAccountJournalType());
//        billDTO.setAccountJournalTypeName(changePlan.getAccountJournalTypeName());
//
//        fundBillService.addBill(billDTO);
//
//        return Result.builder().success();
//    }

    /**
     * 归还冻结金额
     */
//    @Transactional
//    @Override
//    public Result<Void> returnFundManage(String param) {
//        JSONObject jbc = JSON.parseObject(param);
//        if (StringUtils.isBlank(jbc.getString("data"))) {
//            KLog.warn("【归还冻结金额】传入数据异常,入参:{}", param);
//            return Result.builder().fail(BizCodeMessages.VALIDATOR_ERR, "传入数据异常");
//        }
//
//        String decryptStr = AesEncryptUtil.base64AesDecrypt(jbc.getString("data"));
//        KLog.info("【归还冻结金额】解密后的数据:{}, 入参:{}", decryptStr, param);
//
//        if (StringUtils.isBlank(decryptStr)) {
//            KLog.warn("【归还冻结金额】读取数据失败, 解密后的数据:{} ,入参:{}", decryptStr, param);
//            return Result.builder().fail(BizCodeMessages.TRANSACTION_PLEDGE_CHECKING, "读取数据失败");
//        }
//
//        JSONObject dataJbc = JSON.parseObject(decryptStr);
//
//        FundAccountWithdrawPayment withdrawPayment = fundAccountWithdrawPaymentMapper.selectByPrimaryKey(dataJbc.getShort("platNo"), dataJbc.getInteger("fundAccountWithdrawPaymentId"));
//        if (Objects.isNull(withdrawPayment)) {
//            return Result.builder().fail(BizCodeMessages.TRANSACTION_PLEDGE_CHECKING, "原提现订单不存在");
//        }
//
//        FundAccountWithdrawPayment upWithPay = new FundAccountWithdrawPayment(dataJbc.getShort("platNo"));
//        upWithPay.setFundAccountWithdrawPaymentId(withdrawPayment.getFundAccountWithdrawPaymentId());
//        String remark = LocalDateTime.now() + ",手动归还冻结金额";
//        upWithPay.setRemark(StringUtils.isBlank(withdrawPayment.getRemark()) ? remark : withdrawPayment.getRemark() + ";" + remark);
//        //提现状态改为失败
//        if (!withdrawPayment.getWithdrawStatus().equals(WithDrawStatusEnum.WITHDRAW_STATUS_FAIL.getCode())) {
//            upWithPay.setWithdrawStatus(WithDrawStatusEnum.WITHDRAW_STATUS_FAIL.getCode());   //提现失败
//        }
//        Integer upPay = fundAccountWithdrawPaymentMapper.updateById(upWithPay);
//        BizAssertUtils.assertOne(upPay, "修改提现订单失败");
//
//        return returnFund(dataJbc.getInteger("fundAccountWithdrawPaymentId"), dataJbc.getShort("platNo"));
//    }

    /**
     * 扣掉冻结金额
     */
//    @Override
//    public Result<Void> depositAwardPayQuerySucc(Integer fundAccountWithdrawPaymentId, Short platNo) {
//        KLog.info("【提现】扣掉冻结金额, fundAccountWithdrawPaymentId:{}", fundAccountWithdrawPaymentId);
//
//        FundAccountWithdrawPayment withdrawPayment = fundAccountWithdrawPaymentMapper.selectByPrimaryKey(platNo, fundAccountWithdrawPaymentId);
//
//        FundAccountChangePlan changePlan = fundAccountChangePlanMapper
//                .getByOrderId(platNo, withdrawPayment.getOrderSn());
//        changePlan.setPlatNo(platNo);
//
//        //用户账户
//        FundAccount fundAccount = fundAccountMapper.selectByPrimaryKey(withdrawPayment.getFundAccountId());
//        //设置资金主类型
//        Integer accountMainJournalType;
//        if (PlatNoEnums.YXY.isEquals(fundAccount.getPlatNo())) {
//            if (AccountType.getFullCode(AccountType.MER, PlatNoEnums.YXY.getCode()).equals(fundAccount.getAccountType())) {
//                accountMainJournalType = AccountMainJournalType.MERCHANT_OUT.getCode();
//            } else {
//                accountMainJournalType = AccountMainJournalType.ALLY_V2_OUT.getCode();
//            }
//            changePlan.setAccountMainJournalType(accountMainJournalType);
//
//            JournalInfoVO journalVO = ChangeTypeConstant.getSubtractJournalTypeV2(fundAccount.getAccountType(), accountMainJournalType);
//            changePlan.setAccountJournalType(journalVO.getToJournalType());
//            changePlan.setAccountJournalTypeName(journalVO.getUserJournalTypeName());
//            changePlan.setFromAccountJournalType(journalVO.getFromJournalType());
//            changePlan.setFromAccountJournalTypeName(journalVO.getSysJournalTypeName());
//        }
//
//        try {
//            //账户操作
//            withdrawFundOptService.depositAwardPayQuerySuccOpt(changePlan);
//        } catch (UserBizException e) {
//            KLog.warn("【提现】扣掉冻结金额,异常:{}, 资金变动记录:{}", e.getMessage(), changePlan.toString(), e);
//            return Result.builder().fail(BizCodeMessages.TRANSACTION_PLEDGE_CHECKING);
//        } catch (BizRuntimeException e) {
//            KLog.error("【提现】扣掉冻结金额,异常:{}, 资金变动记录:{}", e.getMessage(), changePlan.toString(), e);
//            return Result.builder().fail(BizCodeMessages.TRANSACTION_PLEDGE_CHECKING);
//        }
//
//        return Result.builder().success();
//    }
}
